<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="检验单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reportNumber">
              <a-input v-model="model.reportNumber" placeholder="保存自动生成" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="计划单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="planNumber">
              <a-input v-model="model.planNumber" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="reportType === 'base-powder'">
            <a-form-model-item label="基粉配方" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="basePowderFormula">
              <a-input v-model="model.basePowderFormula" placeholder="请输入基粉配方"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="reportType === 'semi-finished-product'">
            <a-form-model-item label="配方号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="basePowderFormula">
              <a-select
                v-model="model.basePowderFormula"
                placeholder="请选择配方号"
              >
                <a-select-option
                  v-for="(item,index) in qcPlanReportItemTable.dataSource"
                  :key="index"
                  :value="item.formulaNumber">
                  {{ item.formulaNumber }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="抽检数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="samplingQuantity">
              <a-input-number v-model="model.samplingQuantity" placeholder="请输入抽检数量" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="检验日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inspectionDate">
              <j-date placeholder="请选择检验日期" v-model="model.inspectionDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>

    <div 
      style="max-height: 600px; 
                  overflow-y: auto; 
                  margin-top: 10px;
                  border: 1px solid #dcdfe6;  /* 添加边框颜色 */
                  border-radius: 4px;         /* 添加圆角 */
                  padding: 10px;              /* 添加内边距 */
                  box-shadow: 0 2px 4px rgba(0,0,0,.1); /* 添加轻微阴影 */
                  margin-bottom: 10px;">
      <el-card v-for="(card, index) in cardList" :key="index" style="margin-bottom: 10px;">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="检验标准" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag
                placeholder="请选择检验标准"
                @change="handleInspectionStandardChange($event, index)"
                v-model="card.standardId"
                :dict="inspectionStandardCode" 
                :disabled="formDisabled"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="reportType === 'base-powder'">
            <a-form-model-item label="检验时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date date-format='YYYY-MM-DD HH:mm:ss' 
                      v-model="card.inspectionTime" 
                      :disabled="formDisabled"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <j-vxe-table
                style="margin: 10px 0"
                keep-source
                ref="inspectionItemTable_' + index"
                :loading="qcPlanReportInspectionItemTable.loading"
                :columns="qcPlanReportInspectionItemTable.columns"
                :dataSource="card.inspectionItems"
                :maxHeight="300"
                :disabled="formDisabled"
                :rowNumber="true"
                :rowSelection="!formDisabled"
                :toolbar="true"
                :toolbarConfig="{
                  slots: ['prefix', 'suffix'],
                  btn: ['remove', 'clearSelection'],
                }"
                @remove="handleDelete"
              />
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="检验结果" :labelCol="labelCol2" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="radio" 
                                v-model="card.inspectionResult" 
                                dictCode="qc_inspection_result"
                                :disabled="formDisabled"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol">
              <a-textarea v-model="card.remark" :disabled="formDisabled"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </el-card>
    </div>
    <j-vxe-table
      keep-source
      ref="qcPlanReportItem"
      :loading="qcPlanReportItemTable.loading"
      :columns="qcPlanReportItemTable.columns"
      :dataSource="qcPlanReportItemTable.dataSource"
      :maxHeight="300"
      :disabled="formDisabled"
      :rowNumber="true"
      :rowSelection="false"
      :toolbar="false"
      style="margin-top: 18px;"
    />
  </a-spin>
</template>

<script>

import { getAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import dayjs from 'dayjs'

export default {
  name: 'QcPlanReportForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      model: {
        inspectionResult: 1,
        inspectionDate: dayjs().format('YYYY-MM-DD')
      },
      validatorRules: {
      },
      // 检验单检验项目表
      qcPlanReportInspectionItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '检验项目',
            key: 'itemName',
            type: JVXETypes.normal,
            minWidth: '200px'
          },
          {
            title: '上限值',
            key: 'upperLimit',
              type: JVXETypes.normal,
            width:"200px",
            defaultValue:'',
          },
          {
            title: '标准值',
            key: 'qualityStandard',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '下限值',
            key: 'lowerLimit',
              type: JVXETypes.normal,
            width:"200px",
            defaultValue:'',
          },
          {
            title: '结果录入',
            key: 'result',
            type: JVXETypes.normal,
            defaultValue: '',
            width:"200px",
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.normal,
            minWidth:"200px",
            defaultValue:'',
          },
        ]
      },
      cardList: [ // 存储所有卡片数据
        {
          standardId: null,
          inspectionDate: dayjs().format('YYYY-MM-DD'),
          inspectionTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          inspectionResult: 1,
          remark: '',
          inspectionItems: [] 
        }
      ],
      currentCardIndex: 0,
      // 检验单项表
      qcPlanReportItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '订单编号',
            key: 'orderNumber',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '物料编码',
            key: 'materialCode',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal
          },
          {
            title: '规格型号',
            key: 'specificationModel',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '配方号',
            key: 'formulaNumber',
            type: JVXETypes.normal,
            width: '200px'
          }
        ]
      },
      url: {
        add: '/qms/inspection/plan/report/add',
        edit: '/qms/inspection/plan/report/edit',
        queryById: '/qms/inspection/plan/report/queryById',
        qcPlanReportInspectionItem: {
          // list: '/qms/inspection/plan/report/queryQcPlanReportInspectionItemByMainId'
          list: '/qms/inspection/plan/report/queryQcPlanReportInspectionByMainId'
        },
        qcPlanReportItem: {
          list: '/qms/inspection/plan/report/queryQcPlanReportItemByMainId'
        },
        workshopPlanInfo: {
          list: '/pro/tslProWorkshopPlan/queryTslProWorkshopPlanInfoByMainId'
        },
        basePowderInspectionStandardItem: {
          list: '/basiccheck/eneBasicCheck/queryEneBasicCheckDetailByMainId'
        },
        semiFinishedProductInspectionStandardItem: {
          list: '/semifinished/eneSemiFinishedCheck/queryEneSemiFinishedCheckDetailByMainId'
        },
        finishedProductInspectionStandardItem: {
          list: '/finishedproduct/eneFinishedProductCheck/queryEneFinishedProductCheckDetailByMainId'
        }
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    reportType: {
      type: String,
      required: true
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    inspectionStandardCode() {
      if (this.reportType === 'base-powder') {
        return 'ene_basic_check,check_standard,id'
      } else if (this.reportType === 'semi-finished-product') {
        return 'ene_semi_finished_check,check_standard,id'
      } else if (this.reportType === 'finished-product') {
        return 'ene_finished_product_check,check_standard,id'
      }
      return ''
    },
    inspectionStandardItemUrl() {
      if (this.reportType === 'base-powder') {
        return this.url.basePowderInspectionStandardItem.list
      } else if (this.reportType === 'semi-finished-product') {
        return this.url.semiFinishedProductInspectionStandardItem.list
      } else if (this.reportType === 'finished-product') {
        return this.url.finishedProductInspectionStandardItem.list
      }
      return ''
    }
  },
  created() {
  },
  methods: {
    add() {
      this.addBefore()
      this.edit({})
    },
    addBefore() {
      this.qcPlanReportInspectionItemTable.dataSource = []
      this.qcPlanReportItemTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    edit(record) {
      this.addBefore()
      this.model.reportType = this.reportType
      this.model.planNumber = record.code
      this.model.productionShop = record.workshopCode
      this.model.executionDate = record.workTime
      this.editAfter(record)
    },
    editAfter(model) {
      this.fetchWorkshopPlanInfo(model.id)
    },
    async handleSubmit() {
      const validate = await this.$refs.form.validate()
      if (!validate) {
        return
      }
      const errMap = await this.$refs.qcPlanReportInspectionItem.validateTable()
      if (errMap) {
        return
      }
      const formData = {
        ...this.model,
        qcPlanReportItemList: this.qcPlanReportItemTable.dataSource.map(item => {
          return {
            ...item,
            id: null
          }
        }),
        qcPlanReportInspectionItemList: this.qcPlanReportInspectionItemTable.dataSource.map(item => {
          return {
            ...item,
            id: null
          }
        })
      }
      this.request(formData)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    detail(record) {
      this.model = Object.assign({}, record)
      this.cardList = []; // 清空卡片列表
      this.qcPlanReportItemTable.dataSource = []
      this.$nextTick(() => {
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        // this.requestSubTableData(this.url.qcPlanReportInspectionItem.list, params, this.qcPlanReportInspectionItemTable)
        // 加载检验报告数据（卡片数据）
        getAction(this.url.qcPlanReportInspectionItem.list, params).then(res => {
          if (res.success && res.result) {
            this.cardList = res.result.map(report => ({
              id: report.id,
              standardId: report.standardId,
              inspectionDate: report.inspectionDate,
              inspectionTime: report.inspectionTime,
              inspectionResult: report.inspectionResult,
              remark: report.remark,
              inspectionItems: report.qcPlanReportInspectionItemList || []
            }));
          }
        });
        this.requestSubTableData(this.url.qcPlanReportItem.list, params, this.qcPlanReportItemTable)
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([]).then(() => {
          resolve(allValues)
        }).catch(e => {
          console.error(e)
        })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        qcPlanReportInspectionItemList: allValues.tablesValue[0].tableData,
        qcPlanReportItemList: allValues.tablesValue[1].tableData
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    handleInspectionStandardChange(value) {
      const params = { id: value }
      getAction(this.inspectionStandardItemUrl, params).then(res => {
        let { result } = res
        if (result) {
          this.qcPlanReportInspectionItemTable.dataSource = result.map(item => {
            return {
              inspectionStandardId: item.basicId || item.semiId || item.finishedId,
              itemName: item.analyseItem,
              qualityStandard: item.qualityIndex,
              upperLimit: item.upperLimit,
              lowerLimit: item.lowerLimit,
              remark: item.remark,
              result: ''
            }
          })
        }
      })
    },
    fetchWorkshopPlanInfo(id) {
      getAction(this.url.workshopPlanInfo.list, { id: id }).then(res => {
        let { result } = res
        if (result) {
          this.qcPlanReportItemTable.dataSource = result.map(item => {
            return {
              orderNumber: item.orderCode,
              materialCode: item.productCode,
              materialName: item.productBatchNo,
              specificationModel: item.materialSpec,
              formulaNumber: item.formulaNumber
            }
          })
        }
      })
    },
    handleDelete({ deleteRows }) {
      this.qcPlanReportInspectionItemTable.dataSource = this.qcPlanReportInspectionItemTable.dataSource.filter(row =>
        !deleteRows.some(item => item.id === row.id)
      )
    }
  }
}
</script>

<style scoped>
</style>